package com.monkey.algorithm.chapter1.stack

/**
 * 作者：Monkey
 * 日期：2018/1/27
 */
class LinkedStack<T> : Iterable<T> {
    private var n = 0
    private var first: Node? = null

    fun push(item: T) {
        val node = Node(item, first)
        first = node
        n++
    }

    fun pop(): T? {
        return if (isEmpty()) {
            null
        } else {
            val item = first?.item
            first = first?.next
            n--
            item
        }
    }

    fun size() = n

    fun isEmpty() = first == null

    override fun iterator(): Iterator<T> {
        return StackIterator()
    }


    private inner class StackIterator : Iterator<T> {
        var current: Node? = first

        override fun hasNext() = current != null

        override fun next(): T {
            val item = current?.item
            current = current?.next
            return item!!
        }
    }

    private inner class Node(var item: T? = null, var next: Node? = null)
}